package com.zhengshang.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhengshang.api.domain.AppOtherQueryRecord;
import com.zhengshang.api.service.IAppOtherQueryRecordService;
import com.zhengshang.common.annotation.RepeatSubmit;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.express.KdniaoTrackQueryAPI;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HY
 * @version 1.0.0
 * @ClassName ViolationController.java
 * @Description TODO
 * @createTime 2021年04月08日 09:07
 */
@Api(tags = "快递查询接口")
@RestController
@RequestMapping("/express")
public class ExpressController extends BaseController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IAppOtherQueryRecordService appOtherQueryRecordService;

    @ApiOperation(value = "可用快递公司编码查询")
    @PreAuthorize("@ss.hasPermi('app:express:query')")
    @RepeatSubmit
    @PostMapping("/getExpCode")
    public AjaxResult getExpCode(
            HttpServletRequest request, HttpServletResponse response){
        try {

            KdniaoTrackQueryAPI kdniaoTrackQueryAPI = new KdniaoTrackQueryAPI();
            return AjaxResult.success(kdniaoTrackQueryAPI.getExpCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

    @ApiOperation(value = "快递查询", notes = "返回数据可参考官方接口文档：http://www.kdniao.com/api-track")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "expCode", value = "快递公司编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "expNo", value = "物流单号", dataType = "String", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('app:express:query')")
    @RepeatSubmit
    @PostMapping("/query")
    public AjaxResult query(
            @RequestParam String expCode,
            @RequestParam String expNo,
            HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isBlank(expCode) || StringUtils.isBlank(expNo)) {
                return AjaxResult.error("参数异常");
            }
            String countStr = configService.selectConfigByKey("app.express.query.count");//每日查询次数
            int count = Integer.parseInt(countStr);
            LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
            AppOtherQueryRecord appOtherQueryRecord = new AppOtherQueryRecord();
            appOtherQueryRecord.setUserId(loginAppUser.getAppUser().getUserId());
            appOtherQueryRecord.setCreateTime(DateUtils.getNowDate());
            appOtherQueryRecord.setQueryType("2");
            if (appOtherQueryRecordService.getTodayCount(appOtherQueryRecord) >= count) {
                return AjaxResult.error("今日查询次数已达上限，请明天再试吧");
            }
            KdniaoTrackQueryAPI kdniaoTrackQueryAPI = new KdniaoTrackQueryAPI();
            String result = kdniaoTrackQueryAPI.getOrderTracesByJson(expCode, expNo);
            logger.info("<express.query>{}", result);
            JSONObject object = JSONObject.parseObject(result);
            if (object.getBooleanValue("Success")) {
                //保存记录
                appOtherQueryRecord.setResultData(result);
                appOtherQueryRecord.setCreateBy(loginAppUser.getUsername());
                appOtherQueryRecordService.insertAppOtherQueryRecord(appOtherQueryRecord);
                if (object.get("Traces") == null) {
                    return AjaxResult.success("暂无快递信息");
                }
                if (object.get("Traces") instanceof JSONArray) {
                    return AjaxResult.success("查询成功", object.getJSONArray("Traces"));
                }
                return AjaxResult.success("查询成功", object.get("Traces"));
            }
            String Reason = object.getString("Reason");
            return AjaxResult.error(StringUtils.isBlank(Reason) ? "查询失败" : Reason);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("查询失败");
    }

}
